package com.wuda.sample;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.wuda.cfg.Configure;
import com.wuda.util.CharacterTree;
import com.wuda.util.PriorityLinkedQueue;
import com.wuda.util.PriorityLinkedQueue.Order;
import com.wuda.util.Word;

public class TreeTest {

	/**
	 * <p>
	 * 测试加载单词生成树效率,同时返回这棵树
	 * </p>
	 * 
	 * @return {@link CharacterTree}
	 */
	public CharacterTree load() {
		InputStream in = this.getClass().getResourceAsStream(
				Configure.DIC_RESOURCE);
		long startTime = System.currentTimeMillis();
		CharacterTree tree = new CharacterTree();
		BufferedReader reader;
		int count = 0;
		try {
			reader = new BufferedReader(new InputStreamReader(in));
			String word = null;
			while ((word = reader.readLine()) != null) {
				tree.add(word);
				count++;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		long endTime = System.currentTimeMillis();
		System.out.println("共加载单词数：" + count + "，生成tree用时："
				+ (endTime - startTime));
		return tree;
	}

	/**
	 * <p>
	 * 测试前缀查找
	 * </p>
	 * 
	 * @param tree
	 */
	public void findPrefix(CharacterTree tree) {
		InputStream in = this.getClass().getResourceAsStream(
				Configure.DIC_RESOURCE);
		BufferedReader reader;
		long time = 0;
		long startTime = 0;
		long endTime = 0;
		int count = 0;
		try {
			reader = new BufferedReader(new InputStreamReader(in));
			String word = null;
			PriorityLinkedQueue<Word> queue = null;
			String priv = null;
			String prefix = null;
			while ((word = reader.readLine()) != null) {
				queue = new PriorityLinkedQueue<Word>(10, Order.DESC);
				prefix = word.substring(0, 1); // 取一个字符前缀
				if (priv != null && prefix.equals(priv)) {
					// 同一个前缀
					continue;
				}
				priv = prefix;
				startTime = System.currentTimeMillis();
				tree.findPrefix(prefix, queue);
				endTime = System.currentTimeMillis();
				time = time + (endTime - startTime);
				count++;
				Word w = null;
				System.out.println("前缀是：" + prefix + "，查找的词有");
				while ((w = queue.next()) != null) {
					System.out.println(w.getValue());
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		float avg = (float) time / count;
		System.out.println("共查找：" + count + "个前缀，共用时：" + time + "ms,平均用时："
				+ avg + "ms");
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		TreeTest test = new TreeTest();
		CharacterTree tree = test.load();
		test.findPrefix(tree);
	}

}
